/** @odoo-module **/
// 菜品
class cellRenderer {
    init(params) {

        this.owl = params.context.owl_widget;
        let day = params.colDef.field.split('_')[0];
        let data = params.data;
        let color = data[day + '_dish_color_code'];
        let dish_key_id = data[day + '_key_id'] || 0;
        // let cost = data[day + '_dish_key_cost'] || 0; //没有成本的 为 0
        let cost = 0; //没有成本的 为 0
        if(dish_key_id){
            try{
                cost = this.owl.dish_key[dish_key_id].dish_cost;
            }catch (e){

            }
        }
        let spicy = data[day + '_dish_key_spicy'];
        // let taboo = data[day + '_taboo'] || [];
        let value = params.valueFormatted || params.value;
        let dish_key = data[day + '_dish_key'] || {};

        let showTips = false;

        this.dish_key = dish_key;
        this.params = params;
        this.data = data;
        this.day = day;


        let classArr = [];
        !dish_key.is_confirmed && classArr.push('fst-italic');//斜体 未确认
        let tips = [];
        if(cost == 0){
            classArr.push('fw-bolder');
            tips.push('没有配比或配比计算成本为0');
        }
        if(this.owl.state.editConfig.limitCost === '1' && !(dish_key.dish_cost >= data.minCost && dish_key.dish_cost <= data.maxCost)){
            this.owl.state.is_plan_week_show_rule_alert && classArr.push('text-red-underline');//违反规则
            cost < data.minCost && tips.push('成本不能低于'+data.minCost);
            cost > data.maxCost && tips.push('成本不能超过'+data.maxCost);
        }
        if(this.owl.state.editConfig.limitCategory === '1' && data[day + '_limit_category_id'] && data[day + '_limit_category_id'] != dish_key.plan_top_category_id){
            this.owl.state.is_plan_week_show_rule_alert && classArr.push('text-red-underline');//违反规则
            tips.push('不是'+data[day + '_limit_category_name']);
        }

        let current_week = dish_key_id && this.owl.countRowData.dish_key_id[dish_key_id];
        if(data.isSpecialGroups){//特色配菜不计算本周重复
            current_week = 0;
        }
        if(data.dinner_type == 'dn2'||data.dinner_type == 'dn3'){
            if(data[day + '_past_week_2']>0){//上上周出现
                tips.push('上上周重复'+data[day + '_past_week_2']+'次');
                this.owl.state.is_plan_week_show_freq_alert && classArr.push('text-success');
            }
            if(data[day + '_past_week_1']>0){//上周出现
                tips.push('上周重复'+data[day + '_past_week_1']+'次');
                this.owl.state.is_plan_week_show_freq_alert && classArr.push('text-warning');
            }
            if(current_week > 1){
                tips.push('本周重复'+current_week+'次');
                this.owl.state.is_plan_week_show_freq_alert && classArr.push('text-danger');//本周重复
            }
        }
        // 同一餐同一类别菜品不能重复
        let key = 'common';
        if(data.isSpecialGroups){
            key = 'special_'+data.dish_num_id;
        };
        let dish_key_name_arr = [];
        try {
            dish_key_name_arr = this.owl.countRowData[day][data.dinner_type_id][key][data.dish_top_category_id].dish_key_name;
        }catch (e) { }
        let sameNum = getSameNum(value,dish_key_name_arr);//该菜品这一餐这一类别已有这个菜
        if(sameNum>1){
            key == 'common' && tips.push(`这一餐的${data.dish_top_category_name_cn}有${sameNum}个${value}`);
            key != 'common' && tips.push(`这一餐的${data.number_category.name}配菜-${data.dish_top_category_name_cn}有${sameNum}个${value}`);
            this.owl.state.is_plan_week_show_freq_alert && classArr.push('text-danger');
        }

        dish_key.status != '使用' && classArr.push('text-grey'); //不可用或过季

        let el = document.createElement('div');
        let tooltip;
        let _html = '';
        let tooltipTePei = [];
        el.className='day_dish_cell';
        el.setAttribute('style','white-space: normal;line-height: 15px;padding:6px');
        if(params.value != "" && params.value != undefined){
            // 菜品颜色
            if (this.owl.state.tableConfig.color) {
                _html += `<span class="dot ${color?'':'dot-0'}" style="background: ${color}"></span>`;
            }

            let name = value.split('/')[0];

            _html += `<span class="${classArr.join(' ')} day_dish_value" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="bottom" data-bs-title="${tips.join('，')}">${name}</span>`;

            // 辣度 spicy
            if (spicy && this.owl.state.tableConfig.spicy) {
                _html += this.owl.spicyHtml(spicy)
            }
            // 成本 cost
            if (cost && this.owl.state.tableConfig.cost) {
                _html += `<span class="cost-tag">￥${cost}</span>`;
            }

            // 配菜
            if(data.te_pei_json && data.te_pei_json[day].length > 0){
                data.te_pei_json[day].forEach((pei,peiIndex)=>{
                    let isRed = false;
                    if(!(this.owl.dish_key[pei] && this.owl.dish_key[pei].dish_top_category_id) || !dish_key_id){
                        isRed = true;
                        tooltipTePei.push(peiIndex);
                    }
                    if(isRed){
                        _html += `<span style="text-decoration: underline;text-decoration-color: red;" class="day_dish_pei_${peiIndex}" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="bottom" data-bs-title="${dish_key_id?'请右键为该菜品设置类别，否则将保存失败':'没有特色，请修改'}">/${this.owl.dish_key[pei].name}</span>`;
                    }else{
                        _html += `<span class="day_dish_pei_${peiIndex}" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="bottom" data-bs-title="${dish_key_id?'请右键为该菜品设置类别，否则将保存失败':'没有特色，请修改'}">/${this.owl.dish_key[pei].name}</span>`;
                    }
                })
            }
            el.innerHTML = _html;


            let TooltipElTePei = [];
            tooltipTePei.forEach((v,i)=>{
                TooltipElTePei.push(el.getElementsByClassName('day_dish_pei_'+i)[0]);
                tooltipTePei[i] = bootstrap.Tooltip.getOrCreateInstance(TooltipElTePei[i]);
            })
            this.tooltipTePei = tooltipTePei;

            let TooltipEl = tips.length>0 && el.getElementsByClassName('day_dish_value')[0];
            TooltipEl && (tooltip = bootstrap.Tooltip.getOrCreateInstance(TooltipEl));
            showTips = (this.owl.needShowTipCell.id == data.id && day == this.owl.needShowTipCell.day);
            if(showTips && tooltip){
                //刚修改 显示提示 两秒钟后消失
                setTimeout(()=>{
                    try {
                        tooltip.show();
                        this.owl.needShowTipCell = {};
                        setTimeout(()=>{
                            tooltip.hide();
                        },2000)
                    }catch(e){
                        // console.log(e);
                    }
                },500)
            }
            if(showTips && !tooltip){
                this.owl.needShowTipCell = {};
            }


            if(data.te_pei_json && dish_key_id){
                el.setAttribute('draggable',true);
            }
            if(!data.te_pei_json){
                el.setAttribute('draggable',true);
            }

        }

        if(this.params.colDef.editable(params)){
            el.setAttribute('allowdrop',true);
        }
        this.eGui = el;
        this.tooltip = tooltip;

        this.onDragOverListener = this.onDragOver.bind(this);
        this.eGui.addEventListener('dragover', this.onDragOverListener);

        this.onDragEnterListener = this.onDragEnter.bind(this);
        this.eGui.addEventListener('dragenter', this.onDragEnterListener);

        this.onDropListener = this.onDrop.bind(this);
        this.eGui.addEventListener('drop', this.onDropListener);

        if(params.value != "" && params.value != undefined){
            this.onDragStartListener = this.onDragStart.bind(this);
            this.eGui.addEventListener('dragstart', this.onDragStartListener);
        }
    }

    onDragOver(event){
        let dropbox = event.target.closest('[allowdrop]');
        if (dropbox) {
            event.preventDefault()
        }
    }
    onDragEnter(event){
        event.preventDefault();
        let params = this.params;
        let data = this.data;
        let day = this.day;
        let dragingData = this.owl.dragingData;
        if (this.owl.lastDrop) {
            this.owl.lastDrop.toggleAttribute('over',false);
            this.owl.lastDrop.toggleAttribute('candrop',false);
            this.owl.lastDrop.toggleAttribute('repeat',false);
            this.owl.lastDrop.toggleAttribute('same',false);
        }
        let dropbox = event.target.closest('[allowdrop]'); // 获取最近的放置目标
        if (dropbox) {
            dropbox.toggleAttribute('over',true);
            let key = 'common';
            if(data.isSpecialGroups){
                key = 'special_'+data.dish_num_id;
            }
            let isOwned = this.owl.countRowData[day][data.dinner_type_id][key][data.dish_top_category_id].dish_key_name.includes(dragingData.name);//该菜品这一餐这一类别已有这个菜
            let isSameDay = dragingData.from && dragingData.from.day == day;//同一天
            let isSameTopCategory = dragingData.dish_top_category_id == data.dish_top_category_id; //同个类别
            let isSameDish = isSameTopCategory &&  dragingData.name == params.value; //同个菜

            if(isSameTopCategory && !isSameDish){
                if(!isOwned){
                    dropbox.toggleAttribute('candrop',true);
                }
                if(isOwned && isSameDay){ //同一餐有两个相同的菜品 只能交换 不能复制
                    dropbox.toggleAttribute('candrop',true);
                }
                if(isOwned && !isSameDay){
                    dropbox.toggleAttribute('repeat',true);
                }
            }
            if(isSameDish){
                dropbox.toggleAttribute('same',true);//相同菜品
            }
            this.owl.lastDrop = dropbox;
        }
    }

    onDrop(event){
        event.preventDefault();
        let params = this.params;
        let data = this.data;
        let day = this.day;
        // console.log(event);
        // let jsonData = event.dataTransfer.getData('application/json');
        // let resData = JSON.parse(jsonData);
        let dragingData = this.owl.dragingData;
        // let lastDrop = this.owl.lastDrop;
        let key = 'common';
        if(data.isSpecialGroups){
            key = 'special_'+data.dish_num_id;
        }
        let isOwned = this.owl.countRowData[day][data.dinner_type_id][key][data.dish_top_category_id].dish_key_name.includes(dragingData.name);//该菜品这一餐这一类别已有这个菜
        let isSameDay = dragingData.from && dragingData.from.day == day;//同一天
        let isSameTopCategory = dragingData.dish_top_category_id == data.dish_top_category_id; //同个类别
        let isSameDish = isSameTopCategory &&  dragingData.name == params.value; //同个菜

        // console.log('onDrop');
        // console.log(params);
        if(dragingData.from && isSameTopCategory && !isSameDish){
            if(!isOwned){
                this.owl.startEditingCell(params.node.rowIndex,params.colDef.field,JSON.stringify(dragingData));
            }
            if(isOwned && isSameDay){ //同一餐有两个相同的菜品 直接交换
                let rowNode = params.api.getRowNode(data.id);
                rowNode.setDataValue(day+'_dish_key_name',dragingData.name);
                let rowNode_1 = params.api.getRowNode(dragingData.from.id);
                rowNode_1.setDataValue(dragingData.from.day+'_dish_key_name',params.value);
            }
        }

        if(!dragingData.from && isSameTopCategory && !isSameDish){
            if(!isOwned){
                let rowNode = params.api.getRowNode(data.id);
                rowNode.setDataValue(day+'_dish_key_name',dragingData.name);
            }
        }
    }

    onDragStart(dragEvent) {
        // var userAgent = window.navigator.userAgent;
        let _this = this;
        let params = _this.params;
        let jsonObject = _this.dish_key;
        if(this.data.te_pei_json){
            jsonObject.te_pei_json = this.data.te_pei_json[this.day];
        }
        let jsonData = JSON.stringify(jsonObject);
        jsonObject.from = {
            id:params.data.id,
            day:_this.day,
        };
        // console.log(jsonObject);
        dragEvent.dataTransfer.setData('application/json', jsonData);
        dragEvent.dataTransfer.setData('text/plain', jsonData);
        this.owl.dragingData = jsonObject;

        // this.eGui.toggleAttribute('allowdrop',false);
    }



    getGui() {
        return this.eGui;
    }

    refresh(params) {
        return false;
    }

    destroy() {
        this.eGui.removeEventListener('dragstart', this.onDragStartListener);
        this.tooltip && this.tooltip.dispose();
        this.tooltipTePei && this.tooltipTePei.forEach(v=>{
            v.dispose();
        })
    }
}

/**
 * 获取数组中相同元素的个数
 * @param val 相同的元素
 * @param arr 传入数组
 */
function getSameNum(val,arr){
    let processArr = arr.filter(function(value) {
        return value == val;
    })
    return processArr.length;
}


export default cellRenderer
